package org.apogee.mil.client.main.pages.admin.forms.widgets;

import java.util.ArrayList;

import org.apogee.mil.client.factories.ServerServiceFactory;
import org.apogee.mil.client.main.pages.trainer.widgets.ViewTraineeWidget;
import org.apogee.mil.client.utils.Session;
import org.apogee.mil.shared.Constants.DisplayFormat;
import org.apogee.mil.shared.User;

import com.extjs.gxt.ui.client.data.BaseModel;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedListener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.CheckBox;
import com.extjs.gxt.ui.client.widget.form.SimpleComboBox;
import com.extjs.gxt.ui.client.widget.grid.CellEditor;
import com.extjs.gxt.ui.client.widget.grid.CheckColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.RowEditor;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;

public class TraineeWidget implements IsWidget {
	private ColumnModel cm;

	private ListStore<BaseModel> store = new ListStore<BaseModel>();

	private User currentUser;

	private SimpleComboBox<String> userCombo;

	private boolean editable;
	
	private String selectedTrainee = "";

	private IsWidget traineeWidget;
	
	private boolean showHeader;
	
	public TraineeWidget() {
		this(null);
	}

	public TraineeWidget(IsWidget traineeWidget) {
		this.currentUser = ServerServiceFactory.getUser(Session.getSessionId());
		userCombo = new SimpleComboBox<String>();
		this.editable = traineeWidget == null ? true : false;
		this.traineeWidget = traineeWidget;
		
		showHeader = traineeWidget == null ? false : true;
		getUsers();
	}

	private void getUsers() {
		if (editable == false) {
			return;
		}
		ServerServiceFactory.getAdminService(Session.getSessionId()).getUsers(currentUser.getAccessLevel(), new AsyncCallback<ArrayList<BaseModel>>() {

			@Override
			public void onSuccess(ArrayList<BaseModel> result) {
				for (BaseModel bm : result) {
					userCombo.add(bm.get(DisplayFormat.USER_FMT).toString());
				}
				userCombo.getView().refresh();

			}

			@Override
			public void onFailure(Throwable caught) {

			}
		});

	}

	@Override
	public Widget asWidget() {
		ContentPanel cp = new ContentPanel();
		cp.setHeading("Trainees");
		cp.setHeaderVisible(showHeader);
		cp.setAutoHeight(true);
		cp.setWidth(260);
		cp.setBorders(true);

		ArrayList<ColumnConfig> configs = new ArrayList<ColumnConfig>();

		CellEditor editor = new CellEditor(userCombo){
			@Override
			public Object preProcessValue(Object value) {
				if (value == null) {  
					return value;  
				}  
				return userCombo.findModel(value.toString());

			}

			@Override  
			public Object postProcessValue(Object value) {  
				if (value == null) {  
					return value;  
				}  

				return ((ModelData) value).get(DisplayFormat.DEFAULT);  
			}  
		};

		ColumnConfig column = new ColumnConfig();
		column.setId(DisplayFormat.USER_FMT);
		column.setHeader("Trainee");
		column.setRowHeader(true);
		column.setWidth(200);

		if (editable) {
			column.setEditor(editor);
		}
		configs.add(column);

		CheckColumnConfig delColumn = new CheckColumnConfig(DisplayFormat.DELETE, "Delete", 50);
		CellEditor delColEditor = new CellEditor(new CheckBox());
		delColumn.setEditor(delColEditor);
		if (editable) {
			configs.add(delColumn);
		}
		cm = new ColumnModel(configs);

		final RowEditor<BaseModel> re = new RowEditor<BaseModel>();

		GWT.log("Trainee Widget");
		
		Grid<BaseModel> grid = new Grid<BaseModel>(store, cm);
		grid.setBorders(true);
		grid.setColumnLines(true);
		grid.getAriaSupport().setLabelledBy(cp.getHeader().getId()+"-label");
		grid.setSize(260, 400);
		
		if (editable) {
			grid.addPlugin(re);
		}
		
		grid.getSelectionModel().addSelectionChangedListener(new SelectionChangedListener<BaseModel>() {

			@Override
			public void selectionChanged(SelectionChangedEvent<BaseModel> se) {
				BaseModel bm = se.getSelectedItem();
				
				selectedTrainee = bm.get(DisplayFormat.USER_FMT).toString();
				
				if (traineeWidget != null && traineeWidget instanceof ViewTraineeWidget) {
					((ViewTraineeWidget) traineeWidget).update(selectedTrainee);
				}

			}
		});

		cp.add(grid);

		ToolBar tb = new ToolBar();
		Button add = new Button("Add Trainee To Trainer");
		add.addSelectionListener(new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {
				BaseModel bm = new BaseModel();
				bm.set(DisplayFormat.NEW, DisplayFormat.NEW);
				re.stopEditing(false);
				store.insert(bm, store.getCount());
				re.startEditing(store.indexOf(bm), true);

			}
		});

		if (editable) {
			tb.add(add);

			cp.setTopComponent(tb);
		}
		return cp;
	}

	public ListStore<BaseModel> getStore() {
		return store;
	}
	
	public String getSelectedTrainee() {
		return selectedTrainee;
	}

	public void update(final int trainerId) {		
		ServerServiceFactory.getTrainerService(Session.getSessionId()).getTrainees(trainerId, new AsyncCallback<ArrayList<BaseModel>>() {

			@Override
			public void onSuccess(ArrayList<BaseModel> result) {
				store.removeAll();
				store.add(result);

			}

			@Override
			public void onFailure(Throwable caught) {
				MessageBox.alert("Error", "Unable to get trainees for trainer with id: " + trainerId, null);
			}
		});

	}

}
